#args = commandArgs(TRUE);
library("quantmod");
source("scripts2/sim.R")
#rm(list=ls())
Debug = F;
stock_list = read.csv("hold_list.txt", head=T);
stock_profit = read.csv("hold_profit.txt", head=T);

stock_index = 1;
hold_stock = data.frame(cbind("Name", 8.88, 0.20, "2013-08-06"));
colnames(hold_stock) = c("Name", "Price", "Profit", "BuyDate");

today = as.character(Sys.Date());
for (stock_name in stock_list$Name) {
    #print (stock_name);
    try ({
    stock = getSymbols(stock_name, auto.assign=F);
    stock_close = stock[,4];
    total_length = length(stock_close);

    stock_macd2 = MACD(stock_close, 10, 30, 13);
    stock_macd = MACD(stock_close, 7, 35, 10);
                
    stock_macd_diff = stock_macd[,1] - stock_macd[,2];
    stock_BB = BBands(stock_close, n=10);

    recur = total_length;
    final_price = stock_close[total_length];
    init_price = stock_list$Price[stock_index];
    buy_date = as.character( stock_list$BuyDate[stock_index] );
    
                
    class(final_price) <- "numeric";
    class(init_price) <- "numeric";
    sell_stock  = sell(Debug, recur, stock_close, stock_macd[,1], stock_macd2[,2], stock_macd_diff, stock_BB);
    if (     
        sell_stock == T # Sell this stock
    ) {           
        
        profit = (final_price - init_price) / init_price;
        #stock_profit[stock_profit_insert, ] = c(stock_name, profit);
        print( paste("Sell :", stock_name,", Price = " , final_price , ", buy_price = ", init_price,  ", profit = ", profit, ", but_date:", buy_date ) );
        # Move record to hold_profit file.
        profit_record= data.frame(cbind(stock_name, profit, buy_date, today ));
        colnames(profit_record) = colnames(stock_profit);          
        stock_profit = rbind(stock_profit, profit_record);
    }
    else { # hold this stock
        
        profit = (final_price - init_price) / init_price;
        record = data.frame(cbind(stock_name, init_price, profit, buy_date));
        colnames(record) = colnames(hold_stock);
        hold_stock = rbind(hold_stock, record);
        #print( paste( "Retain:" , stock_name, ", buy:", init_price, ", current:", final_price) );            
    }

    }) # End of Try
    stock_index = stock_index + 1;
} # End of Symbol Scan

write.csv(hold_stock, "hold_list.txt", row.names=F);
write.csv(stock_profit, "hold_profit.txt", row.names=F);

